<template>
  <!-- 处理dialog-->
  <el-dialog
    title="事件处置"
    :destroy-on-close="true"
    :visible="visible"
    @open="openFunc"
    :before-close="resetFun"
    class="dialog-class1 scale-dialog dialogStyle"
    width="560px"
  >
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="95px"
      v-loading="loading"
    >
      <el-form-item label="下一环节" prop="flowLink">
        <el-select
          v-model="ruleForm.flowLink"
          clearable
          placeholder="请选择"
          @change="getUserTree"
          style="width: 100%"
        >
          <el-option
            v-for="item in nextLinkList"
            :key="item.linkId"
            :label="item.linkName"
            :value="item.curLink"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-row v-if="nextLinkList.length > 0 && ruleForm.flowLink != 6">
        <el-col class="input">
          <el-form-item label="处理人" prop="userList" class="select-user">
            <tree-select
              ref="treeSelect"
              v-model="ruleForm.userList"
              :allUserTreeData="allUserTreeData"
              :userTreeData="userTreeData"
              node-key="id"
              default-expand-all
              show-checkbox
              :config="{ label: 'userName', value: 'userId' }"
              :isShowAllBtn="isShowAllBtn"
              :isShowAllInfo.sync="isShowAllInfo"
              :nextLinkInfo="
                this.nextLinkList.find(
                  (item) => item.curLink == this.ruleForm.flowLink
                )
              "
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="position-info">
        <editUsefulWord
          :isShowUsefulWord.sync="isShowUsefulWord"
        ></editUsefulWord>
      </div>
      <el-form-item label="处置结果" class="small" prop="desc">
        <el-input
          type="textarea"
          v-model="ruleForm.desc"
          @input="ruleForm.desc = ruleForm.desc.replace(/\s+/g, '')"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item v-show="isShowUsefulWord">
        <useful-word
          style="margin-top: -19px"
          :desc.sync="ruleForm.desc"
          :isShowUsefulWord.sync="isShowUsefulWord"
        ></useful-word>
      </el-form-item>
      <el-form-item prop="orderFileDTOList">
        <FormItemIconTipLabel slot="label" />
        <EventFileUpload
          v-model="ruleForm.orderFileDTOList"
          :loading.sync="uploading"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        @click="submitFun('ruleForm')"
        type="primary"
        :loading="btnLoading || uploading"
        style="margin-right: 10px"
        >确 定</el-button
      >
      <el-button @click="resetFun">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { $store, $getUrlParam } from "@/utils/public";
import {
  queryFlowLink,
  queryNextLink,
} from "@/api/modules/eventManagement/eventDialog/trueWarnDialog.js";
import { getUserTree } from "@/api/modules/eventManagement/eventDispatch.js";
import { submitProcessOrder } from "@/api/modules/eventManagement/eventDeal.js";
import { rollBack } from "@/api/modules/eventManagement/eventCheck";
import { getFlow } from "@/api/modules/eventManagement/getFlowId";
import TreeSelect from "@/components/TreeSelect";
import UsefulWord from "@/views/pages/eventManagement/eventDialog/usefulWord";
import editUsefulWord from "@/views/pages/eventManagement/eventDialog/editUsefulWord";
import ElImageViewer from "@/components/ElImgViewer";
import EventFileUpload from "../components/EventFileUpload";
import FormItemIconTipLabel from "../components/FormItemIconTipLabel";
export default {
  name: "handleDialog",
  components: {
    TreeSelect,
    UsefulWord,
    editUsefulWord,
    ElImageViewer,
    EventFileUpload,
    FormItemIconTipLabel,
  },
  data() {
    var validateF = (rule, value, callback) => {
      if (value.length == 0) {
        callback(new Error("请上传附件"));
      } else {
        callback();
      }
    };
    return {
      imageUrl: "",
      dealMan: "",
      flowId: "",
      flowTemplate: "",
      flowLink: "",
      flowLinkOut: "",
      userList: [],
      usersId: [],
      usersName: [],
      backLinkList: [],
      nextLinkList: [],
      allow_img: false,
      allow_video: false,
      imageList: [],
      videoList: [],
      order: {
        docVoList: [],
      },
      uploadFileAction: "/problem/docApi/uploadFile",
      dialogImageUrl: "",
      dialogVisible: false,
      orgName: $store.get("$loginInfo").orgName,
      userName: $store.get("$loginInfo").userName,
      ruleForm: {
        ifFinish: "1",
        desc: "",
        flowLink: "",
        userList: [],
        flowLinkOut: "",
        orderFileDTOList: [],
      },
      userTreeData: [],
      allUserTreeData: [],
      rules: {
        ifFinish: [
          { required: true, message: "请选择", trigger: ["blur", "change"] },
        ],
        // type: [
        //   {required: true, }
        // ],
        flowLink: [
          {
            required: true,
            message: "请选择环节",
            trigger: ["blur", "change"],
          },
        ],
        userList: [
          {
            required: true,
            message: "请选择人员",
            trigger: ["blur", "change"],
          },
        ],
        flowLinkOut: [
          {
            required: true,
            message: "请选择环节",
            trigger: ["blur", "change"],
          },
        ],
        desc: [
          {
            required: false,
            message: "请输入处置结果",
            trigger: ["blur", "change"],
          },
        ],
        orderFileDTOList: [
          {
            required: true,
            type: "array",
            min: 1,
            message: "请上传附件",
            trigger: "change",
            validator: validateF,
          },
        ],
      },
      fileList: [],
      fileNum: 0, //附件个数
      imageUrlList: [],
      videoUrlList: [],
      tempImageList: [],
      tempVideoList: [],
      dialogVisible1: false,
      videoUrl: null,
      fileStatus: false,
      loading: false,
      isTenantAdmin: this.$store.getters.userInfo.isTenantAdmin, // 1 租户管理员
      isShowAllBtn: false /** 是否显示全部处理人按钮 */,
      isShowAllInfo: false, // 是否显示全部处理人
      isShowUsefulWord: false, // 是否显示常用语列表
      btnLoading: false,
      showImgViewer: false,
      selectImgIndex: 0,
      uploading: false,
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    orderData: {
      type: Object,
      default: {},
    },
    orderId: {
      type: String,
      default: "",
    },
  },
  methods: {
    isFinishChange() {
      // this.ruleForm.flowLink = '';
      // this.ruleForm.userId = [];
      // this.ruleForm.flowLinkOut = '';
    },
    //获取操作人员列表
    getUserId(linkId) {
      const _this = this;
      if (!_this.ruleForm.flowLink) {
        _this.ruleForm.userId = [];
      }
      let params = {
        flowId: _this.flowId,
        linkId: linkId,
        orgId: _this.orderData.orgRecord,
        warningSource: _this.orderData.warningSource,
        templateId: _this.orderData.flowTemplate,
      };
      queryFlowLink(params).then((res) => {
        if (res.code === 200) {
          let userName = res.data[0].userName.split(",");
          let userId = res.data[0].userId.split(",");
          let nameData = [];
          for (let i in userName) {
            nameData.push({
              userName: userName[i],
              userId: userId[i],
            });
          }
          _this.userList = nameData;
        }
      });
    },
    getUserName(ids) {
      this.usersId = [];
      this.usersName = [];
      let selectInfo = {};
      for (let i in ids) {
        selectInfo = this.userList.find((item) => item.userId == ids[i]);
        this.usersId.push(selectInfo.userId);
        this.usersName.push(selectInfo.userName);
      }
    },
    async init() {
      const _this = this;
      let params = {
        curLink: _this.orderData.linkId,
      };

      await _this.selectNextLinkList();
    },

    async selectNextLinkList() {
      const _this = this;
      let params = {
        curLink: _this.orderData.linkId,
        flowId: _this.flowId,
        warningSource: _this.orderData.warningSource,
        templateId: _this.orderData.flowTemplate,
      };
      const res = await queryNextLink(params);
      if (res.code === 200) {
        _this.nextLinkList = res.data;
        if (_this.nextLinkList && _this.nextLinkList.length == 1) {
          _this.ruleForm.flowLink = res.data[0].linkId;
          this.getUserTree(_this.ruleForm.flowLink);
        }
      }
    },
    getFlowIds(tenantId, warningSource, alarmCode) {
      const _this = this;
      getFlow({
        tenantId: tenantId,
        warningSource: warningSource,
        alarmCode: alarmCode,
      }).then((resp) => {
        if (resp.code == 200) {
          let flowFlow = tenantId + "_" + warningSource;
          // flowId = resp.data.flowId;
          _this.flowId = resp.data[flowFlow];
          _this.flowTemplate = _this.orderData.flowTemplate
            ? _this.orderData.flowTemplate
            : _this.flowId;
        } else {
          console.log("");
        }
      });
    },

    async openFunc() {
      this.ruleForm.orderFileDTOList = [];
      this.loading = false;
      this.btnLoading = false;
      const _this = this;
      // let params = {
      //   curLink: 2,
      //   flowId: _this.orderData.flowId
      // };
      _this.flowTemplate = _this.orderData.flowTemplate;
      if (!_this.orderData.flowId && !_this.flowId) {
        _this.getFlowIds(
          _this.orderData.tenantId,
          _this.orderData.warningSource,
          _this.orderData.warningTypeId
        );
      } else {
        _this.flowId = _this.flowId ? _this.flowId : _this.orderData.flowId;
      }
      // await queryNextLink(params).then((res) => {
      //     if (res.code === 200) {
      //       debugger
      //       _this.nextLinkList = res.data;
      //     }
      //   });
      // queryRollbackLink({
      //   orderId: _this.orderId,
      //   linkId: _this.orderData.linkId,
      // }).then((res) => {
      //   if (res.code === 200) {
      //     _this.backLinkList = res.data;
      //     _this.ruleForm.flowLinkOut = res.data[0].linkId;
      //   }
      // });
      await _this.init();
    },

    //提交
    submitFun(formName) {
      let _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (_this.ruleForm.desc.length > 255) {
            $message.warning("处置结果不能超过255字！");
            return;
          }
          let flowDataInfo = {};
          if (_this.ruleForm.ifFinish === "1") {
            for (let i = 0; i < _this.nextLinkList.length; i++) {
              let row = _this.nextLinkList[i];
              if (row.curLink == _this.ruleForm.flowLink) {
                flowDataInfo = row;
                break;
              }
            }
          } else {
            for (let i = 0; i < _this.backLinkList.length; i++) {
              let row = _this.backLinkList[i];
              if (row.linkId == _this.ruleForm.flowLinkOut) {
                flowDataInfo = row;
                break;
              }
            }
          }
          flowDataInfo.nextEnableAcceptanceMode =
            flowDataInfo.enableAcceptanceMode;
          flowDataInfo.enableAcceptanceMode =
            this.orderData.enableAcceptanceMode;
          if (_this.ruleForm.ifFinish == "1") {
            let params = {
              ...flowDataInfo,
              flowId: _this.flowId,
              flowTemplate: _this.flowTemplate,
              orderId: _this.orderData.warningOrderId,
              warningOrderId: _this.orderData.warningOrderId,
              linkId: flowDataInfo.curLink,
              // "operator": $store.get("$loginInfo").userId,
              processOrderVOList: [
                {
                  //处理对象
                  orderStatus: _this.ruleForm.ifFinish, //处理结果
                  processOpinion: _this.ruleForm.desc, //处理意见
                  processImgList: _this.ruleForm.orderFileDTOList,
                },
              ],
              voice: "",
            };
            params.cityId = this.orderData.cityId;
            params.countyId = this.orderData.countyId;
            params.provinceId = this.orderData.provinceId;
            params.ifFinish = _this.ruleForm.ifFinish;
            params.flowLink = _this.ruleForm.flowLink;
            // params.userId = _this.usersId.toString();
            // params.userName = _this.usersName.toString();
            params.isNextLink = "1";
            params.isSign = "1"; // 是否会签，1 是， 0 否
            params.processDTOList = [];
            params.devicePitch = this.orderData.devicePitch; // 俯仰角
            params.alarmReason = this.orderData.alarmReason; // 告警原因
            params.deviceHorizontal = this.orderData.deviceHorizontal; // 水平角
            for (let i in _this.usersName) {
              params.processDTOList.push({
                processId: _this.usersId[i],
                processName: _this.usersName[i],
                groupId: "",
              });
            }
            params.flowLinkOut = _this.ruleForm.flowLinkOut;
            if (this.ruleForm.flowLink != "6") {
              // 有下一环节
              params.realLinkType = this.nextLinkList.filter(
                (item) => item.linkId == this.ruleForm.flowLink
              )[0].realLinkType;
              params.flowLinkType = "0";
              params.processDTOList = this.ruleForm.userList.map((ele) => ({
                processId: ele.userId,
                processName: ele.userName,
              }));
            } else {
              // 下一环节为完结
              params.realLinkType = "6";
              params.flowLinkType = "0";
              params.processDTOList = [];
            }
            if (this.orderData.updateAddress) {
              params.address = this.orderData.address;
              params.longitude = this.orderData.longitude;
              params.latitude = this.orderData.latitude;
              params.gridId = this.orderData.gridId;
              params.gridName = this.orderData.gridName;
              params.horiAzimuthAngle = this.orderData.horiAzimuthAngle;
              params.checkGridFlag = "1"; // 是否修改网格员  1 是  0 否
            } else {
              params.checkGridFlag = "0";
            }
            // params.processOrderVOList.processImgList=processList;
            /**
                        if (!this.fileStatus) {
                            this.$message.warning('请等待附件上传完成')
                            return
                        }
                        */
            this.btnLoading = true;
            submitProcessOrder(params).then((resp) => {
              this.btnLoading = false;
              let msgId = {
                id: this.orderData.warningOrderId,
                status: this.orderData.orderStatus,
              };
              this.$store.dispatch("closeSocketMsg", msgId);
              if (resp && resp.code == 200) {
                let userId = this.$store.getters.userInfo.userId;
                if (
                  ((Array.isArray(this.ruleForm.userList) &&
                    this.ruleForm.userList.find(
                      (item) => item.userId == userId
                    )) ||
                    this.isTenantAdmin == "1") &&
                  this.ruleForm.flowLink != "6"
                ) {
                  // 有下一环节处理权限就自动打开下一环节
                  this.$store.dispatch("tagsView/delView", this.$route);
                  this.refreshSelectedTag(this.$route, params.realLinkType);
                } else {
                  _this.onSuccess();
                }
                _this.resetForm();
                $message.success("处置成功");
              } else {
                $message.warning(resp.msg);
              }
            });
          } else if (_this.ruleForm.ifFinish == "2") {
            let params = {
              ...flowDataInfo,
              flowId: _this.flowId,
              flowTemplate: _this.flowTemplate,
              orderId: _this.orderData.warningOrderId,
              warningOrderId: _this.orderData.warningOrderId,
              linkId: flowDataInfo.linkId,
              currentOrderStatus: "4", //4-处置；5-核实
              backType: "1", //0-回退到调度 1-回退到处置
              reason: _this.ruleForm.desc,
              processOrderVOList: [
                {
                  //处理对象
                  orderStatus: _this.ruleForm.ifFinish, //处理结果
                  processOpinion: _this.ruleForm.desc, //处理意见
                  processImgList: _this.ruleForm.orderFileDTOList, // 附件
                },
              ],
            };
            rollBack(params).then((resp) => {
              if (resp && resp.code == 200) {
                $message.success("回退成功");
                const url =
                  $getUrlParam("pageType") === "false"
                    ? "/eventManagement"
                    : "/eventManagement/myEvent";
                this.$close(url);
              } else {
                $message.warning(resp.msg);
              }
            });
          }
          _this.$emit("update:visible", false);
        }
      });
    },
    resetFun() {
      this.$refs.ruleForm.resetFields();
      this.imageList = [];
      this.videoList = [];
      this.fileList = [];
      this.order.docVoList = [];
      this.userTreeData = [];
      this.isShowAllBtn = false; /** 是否显示全部处理人按钮 */
      this.isShowAllInfo = false; // 是否显示全部处理人
      this.isShowUsefulWord = false; // 是否显示常用语列表
      this.$emit("update:visible", false);
    },

    // 字段转换
    transferTreeData(list) {
      return list.map((node) => {
        const { nodeId, ...rest } = node;
        let nodeName = node.userName || node.nodeName;
        const obj = {
          id: nodeId,
          label: nodeName,

          ...rest,
        };
        if (node.children) {
          return {
            ...obj,
            children: this.transferTreeData(node.children),
          };
        }
        return obj;
      });
    },
    getUserTree(linkParam) {
      if (linkParam == "6") {
        return;
      }
      const selectLinkData = this.nextLinkList.filter(
        (item) => item.linkId === linkParam
      );
      this.isShowAllBtn = !(
        selectLinkData[0].dataFilterPermiss === "0" &&
        selectLinkData[0].customAdmin === "1"
      );
      this.isShowAllInfo =
        selectLinkData[0].dataFilterPermiss === "0" && !this.isShowAllBtn;
      const params = {
        curLink: linkParam,
        tenantId: this.$store.getters.userInfo.tenantId
          ? this.$store.getters.userInfo.tenantId
          : this.orderData.tenantId,
        flowId: this.orderData.flowId,
        deviceCode: this.orderData.deviceCode,
        provinceId: this.orderData.provinceId,
        cityId: this.orderData.cityId,
        countyId: this.orderData.countyId,
        warningSource: this.orderData.warningSource,
        gridId: this.orderData.gridId,
        warningTypeId: this.orderData.warningTypeId,
      };
      this.loading = true;
      getUserTree(params).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.userTreeData = this.transferTreeData([res.data.sysPowerInfo]);
          this.allUserTreeData = this.transferTreeData([res.data.sysAllInfo]);
          this.userTreeData[0].root = 1;
          this.allUserTreeData[0].root = 1;
          this.$nextTick(() => {
            this.$refs.treeSelect.checkTreeChange();
          });
        }
      });

      // this.dataList = [];
      // this.generateList(this.userTreeData);

      console.log(
        this.userTreeData,
        params,
        // JSON.parse(JSON.stringify(this.dataList)),
        "this.userTreeData"
      );
    },
    refreshSelectedTag(view, realLinkType) {
      location.reload();
    },
    replaceParamVal(oUrl, paramName, replaceWith) {
      var re = eval("/(" + paramName + "=)([^&]*)/gi");
      var nUrl = oUrl.replace(re, paramName + "=" + replaceWith);
      return nUrl;
    },
    onSuccess() {
      const url =
        $getUrlParam("pageType") === "false"
          ? "/eventManagement"
          : "/eventManagement/myEvent";
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push(url);
    },
    disableContextmenu() {
      return false;
    },
    closeViewer() {
      this.showImgViewer = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.circleButton {
  height: 16px;
  width: 16px;
  border-radius: 50%;
  background-color: orange;
  color: white;
  font-size: 12px;
}

.isShowUpBotton {
  /deep/ .el-upload--picture-card {
    display: none;
  }
  /deep/ .el-upload-list__item-status-label {
    display: none;
  }
}

/deep/ .el-row {
  margin-bottom: 1.5%;
}
/deep/ .el-form-item__error {
  position: relative;
}
/deep/.select-user .el-form-item__error {
  position: absolute;
  top: 35px;
  left: 5px;
}

/deep/ .submitClass {
  background: #ff6a6c !important;
  color: #ffffff !important;
}
/deep/ .isShowVideo {
  display: none !important;
  border: none !important;
}
/deep/ .el-select__tags {
  overflow: auto;
  .el-tag.el-tag--info {
    max-width: 80%;
  }
}
.dialog-class1 /deep/ .el-form-item__label {
  line-height: 36px !important;
}

/deep/ .el-dialog > .el-dialog__body {
  padding: 12px 60px 0px;
}
.image-item {
  height: 55px;
  width: 93px;
  border: 1px solid #eee;
  margin-right: 16px;
  margin-bottom: 15px;
  border-radius: 6px;
  overflow: hidden;
  position: relative;
}
.mask {
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0, 0.7);
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  opacity: 0;
  transition: all 0.3s;
  align-items: center;
  justify-content: center;
  i {
    color: #fff;
    font-size: 22px;
    cursor: pointer;
  }
}
.image-item:hover .mask {
  opacity: 1;
}

.position-info {
  margin-top: -20px;
  padding-right: 5px;
  margin-bottom: 5px;
}
.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 4px;
  }
  /deep/ .el-dialog__header {
    padding: 12px;
  }
  /deep/ .el-dialog__footer {
    padding: 12px;
  }
  /deep/ .el-form-item--small.el-form-item {
    margin-bottom: 12px;
  }
  /deep/ .el-form-item .el-form-item__label {
    padding-right: 9px;
  }
  /deep/ .el-textarea__inner {
    height: 60px;
  }
}
</style>
<style>
.scale-dialog .el-image-viewer__wrapper {
  position: fixed;
  left: -25vw;
  right: -25vw;
  top: -25vh;
  bottom: -25vh;
}
.close-icon .el-dialog__headerbtn {
  top: 10px;
}
</style>
